package shop.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import shop.core.common.bean.JSONResult;
import shop.core.common.dao.page.PagerModel;
import shop.core.common.oscache.SystemManager;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 后台Controller抽象类--controller层的父类
 *
 * @author lintz
 */
public abstract class BaseController<E extends PagerModel> {
    protected Logger logger = LoggerFactory.getLogger(getClass());

//   事先定义空的链接，让继承该类的传值到这边来给后面的return链接使用
    protected String page_toList = null;
    protected String page_toEdit = null;
    protected String page_toAdd = null;

    //返回一个service对象
    public abstract Services<E> getService();

    //自动装配，找到容器中的Bean
    @Autowired
    protected SystemManager systemManager;
    protected JSONResult jsonResult;

    /**
     * 跳转列表页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("toList")
    public String toList(HttpServletRequest request, @ModelAttribute("e") E e) throws Exception {
        e.clear();
        return page_toList;
    }

    /**
     * 公共的查询全部数据
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectAllList")
    @ResponseBody
    public JSONResult selectAllList(HttpServletRequest request, @ModelAttribute("e") E e) throws Exception {
        List<E> rsList = getService().selectList(e);
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询单个对象跳转到编辑页面
     *
     * @param e
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toEdit")
    public String toEdit(@ModelAttribute("e") E e, ModelMap model) throws Exception {
        e = getService().selectOne(e);
        model.addAttribute("e", e);      //数据绑定:将数据库返回对象添加到模型对象，给跳转页面显示用
        return page_toEdit;
    }

    /**
     * 异步编辑单个对象
     * @param e
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toEditJson")
    @ResponseBody
    public JSONResult toEditJson(@ModelAttribute("e") E e, ModelMap model) throws Exception {
        e = getService().selectOne(e);
        jsonResult = new JSONResult();
        jsonResult.setData(e);
        return jsonResult;
    }

    /**
     * 跳转新增页面--每次进行页面跳转都进行clear()
     *
     * @param e
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toAdd")
    public String toAdd(@ModelAttribute("e") E e, ModelMap model) throws Exception {
        e.clear();
        return page_toAdd;
    }

    /**
     * 公共的批量删除数据的方法，子类可以通过重写此方法实现个性化的需求。
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "deletes", method = RequestMethod.POST)
    public String deletes(HttpServletRequest request, String[] ids, @ModelAttribute("e") E e, RedirectAttributes flushAttrs) throws Exception {
        getService().deletes(ids);              //实质也是通过遍历每个id来进行逐个删除
        return "redirect:selectList";           //删除返回查看列表
    }

    /**
     * 公共的批量删除数据的方法，子类可以通过重写此方法实现个性化的需求。--异步删除（json格式）
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "deletesJson", method = RequestMethod.POST)
    @ResponseBody
//    @RequestParam(value = "ids[]"）与前台参数对应
    public String deletesJson(HttpServletRequest request, @RequestParam(value = "ids[]") String[] ids, @ModelAttribute("e") E e, RedirectAttributes flushAttrs) throws Exception {
        getService().deletes(ids);
        return "success";
    }

    /**
     * 公共的删除数据的方法，子类可以通过重写此方法实现个性化的需求。
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "deleteJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deleteJson(HttpServletRequest request, @ModelAttribute("e") E e) throws Exception {
        getService().delete(e);
        jsonResult.setMessage("success");
        return jsonResult;
    }

    /**
     * 公共的更新数据的方法，子类可以通过重写此方法实现个性化的需求。
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(HttpServletRequest request, @ModelAttribute("e") E e, RedirectAttributes flushAttrs) throws Exception {
        getService().update(e);
        return "redirect:selectList";
    }

    /**
     * 公共的更新数据的方法，子类可以通过重写此方法实现个性化的需求。
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "updateJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateJson(HttpServletRequest request, @ModelAttribute("e") E e) throws Exception {
        jsonResult = new JSONResult();
        getService().update(e);
        return jsonResult;
    }

    /**
     * 公共的插入数据方法，子类可以通过重写此方法实现个性化的需求。
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public String insert(HttpServletRequest request, @ModelAttribute("e") E e, RedirectAttributes flushAttrs) throws Exception {
        getService().insert(e);
        return "redirect:selectList";
    }

    /**
     * 公共的插入数据方法，子类可以通过重写此方法实现个性化的需求。
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "insertJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertJson(HttpServletRequest request, @ModelAttribute("e") E e) throws Exception {
        jsonResult = new JSONResult();
        getService().insert(e);
        return jsonResult;          //返回的是一个json格式的信息
    }

    /**
     * 分页获取数据列表
     *
     * @param request 请求
     * @param e       对象参数
     * @return 分页数据模型
     */
    @RequestMapping("loadData")
    @ResponseBody
    public PagerModel loadData(HttpServletRequest request, E e) {
        int offset = 0;                     //每一页开始的偏移量
        int pageSize = 10;                  //每一页的个数
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        PagerModel pager = getService().selectPageList(e);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }
}
